package com.citywithincity.test.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class ApiHttpUtil {
	private static Log log = LogFactory.getLog(ApiHttpUtil.class);
	//private static String cookie;
	public static HttpURLConnection connect(String url, Map<String, String> headers,byte[] content) throws IOException {
		HttpURLConnection connection = createConnection(url,headers,content);
		DataOutputStream out = null;
		try{
			//write
			if(content!=null){
				out = new DataOutputStream(connection.getOutputStream());
				out.write(content);
				out.flush();
			}
		}finally{
			if(out!=null)try{out.close();}catch (Exception e) {}
		}
		return connection;
	}
	
	public static HttpURLConnection createConnection(String url,Map<String, String> headers,byte[] content) throws IOException{
		URL postUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		if(headers!=null){
			for (Entry<String, String> entry : headers.entrySet()) {
				connection.setRequestProperty(entry.getKey(), entry.getValue());
			}
			
		}
		connection.setConnectTimeout(10000);
		connection.setReadTimeout(10000);
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		connection.setRequestProperty("Content-Length", String.valueOf(content.length));
		connection.setChunkedStreamingMode(5);
		return connection;
	}
	
	private static String cookie;
	
	public static String rawPost(String url,Map<String, String> headers, String content) throws  IOException{
		byte[] c = content.getBytes("UTF-8");
		/*File file = new File("D:\\1.jpg");
		byte[] t = new byte[(int) (c.length +0) ];
		System.arraycopy(c, 0, t, 0, c.length);*/
		//写入byte
		//FileInputStream inputStream = new FileInputStream(file);
		//inputStream.read(t, c.length, (int)file.length());
		//inputStream.close();
		return rawPost(url, headers, c);
	}

	public static String rawPost(String url,Map<String, String> headers, byte[] content) throws  IOException{
		StringBuilder sb = new StringBuilder();
		sb.append("Start post:").append(url).append(" data:").append(new String(content));
		log.info(sb.toString());
		HttpURLConnection connection = null;
		BufferedReader reader = null;
		try{
			if(cookie!=null){
				if(headers==null){
					headers = new HashMap<String, String>();
				}
				headers.put("Cookie", cookie);
			}
			connection = connect(url,headers, content);
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			Map<String, List<String>> header = connection.getHeaderFields();
			for (Entry<String, List<String>> entry : header.entrySet()) {
				String key = entry.getKey();
				if("Set-Cookie".equals(key)){
					cookie = entry.getValue().get(0);
					break;
				}
			}
			
			String line;
			sb.setLength(0);
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			log.info(sb.toString());
			return sb.toString();
			
		}finally{
			if(reader!=null){
				try{reader.close();}catch(IOException e){}
			}
			if(connection!=null){
				connection.disconnect();
			}
		}
		
		
	/*	if(cookie!=null){
			connection.setRequestProperty("Cookie",cookie);
		}*/
		
		
		
	/*	}*/
		
		
		
	}
}
